-
Notifications
You must be signed in to change notification settings - Fork 0
/
Deque implementation using doubly linked list.cpp
96 lines (84 loc) · 1.7 KB
/
Deque implementation using doubly linked list.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
using namespace std;
struct NODE {
int data;
NODE *prev;
NODE *next;
};
NODE *front, *rear, *prevnode, *temp;
int empty(){
return (!front);
}
void push_back(int value){
prevnode = rear;
rear = (front == NULL) ? front = new NODE : rear->next = new NODE;
rear->prev = prevnode;
rear->data = value;
rear->next = 0;
}
void push_front(int value){
temp = new NODE;
temp->data = value;
temp->next = front;
if(front) front->prev = temp;
front = temp;
if(front->next == 0) rear = front;
temp->prev = 0;
}
void pop_front(){
temp = front;
if(empty()){
cout << "[DE-QUEUE IS EMPTY]! No element popped." << endl;
} else {
front = temp->next;
if(front){
front->prev = 0;
} else {
rear = 0;
}
delete temp;
}
}
void pop_back(){
NODE *prev;
temp = front;
if(empty()){
cout << "[DE-QUEUE IS EMPTY]! No element popped." << endl;
} else {
while(temp->next != 0){
prev = temp;
temp = temp->next;
}
if(prev->next == 0){
front = 0;
} else {
prev->next = 0;
}
if(temp->next == 0) rear = prev;
delete temp;
}
}
void print(){
if(empty()){
cout << "[EMPTY LIST]" << endl;
} else {
while(!empty()){
cout << front->data;
pop_front();
if(!empty()) cout << " <= ";
}
cout << endl;
}
}
int main(){
push_front(15);
push_front(10);
push_front(5);
push_back(20);
push_back(25);
pop_back();
push_front(2);
pop_front();
pop_back();
print();
}